package com.example.demo.leetcode.top100;

import java.util.HashSet;
import java.util.Set;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _22相交链表
 * @description
 * @date 2023/06/09 15:28
 * <p>
 * ******************************************************
 */
public class _22相交链表 {


    public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
        ListNode tempA = headA;
        ListNode tempB = headB;

        Set<ListNode> set = new HashSet<>();

        while (tempA != null) {
            set.add(tempA);
            tempA = tempA.next;
        }

        while (tempB != null) {
            if (!set.add(tempB)) {
                return tempB;
            }
            tempB = tempB.next;
        }

        return null;

    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode tempA = headA;
        ListNode tempB = headB;

        while (tempA != tempB) {
            if (tempA == null) {
                tempA = headB;
            } else {
                tempA = tempA.next;
            }
            if (tempB == null) {
                tempB = headA;
            } else {
                tempB = tempB.next;
            }
        }

        return tempA;

    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
